package com.log.compone;

import org.junit.Test;

import java.nio.ByteBuffer;

/**
 * @Description Buffer 常用api测试
 * @Author zhaoYi
 * @Date 2024/7/16 21:13
 */
public class BufferTest {

    @Test
    public void testDirect(){
        //申请1kb的直接内存（本地系统）特点：速递快，但耗更高的性能
        ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024);
        System.out.println(directBuffer.isDirect());

        // 申请1kb的普通内存（堆内存-应用内存）
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        System.out.println(buffer.isDirect());
    }

    public static void main(String[] args) {
        // 创建一个容量为10的buffer
        ByteBuffer buffer = ByteBuffer.allocate(10);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("--------------------------------------");
        // 写入数据
        String str= "test";
        buffer.put(str.getBytes());
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("--------------------------------------");
        // 切换为读模式
        buffer.flip();
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
        System.out.println("--------------------------------------");
        // 读取数据,默认读第一个位置的数据
        char aChar = (char) buffer.get();
        System.out.println(aChar);
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());
    }
}
